package controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import dao.AdministratorDao;
import dao.AdministratorPowerDao;
import dao.PowerDao;
import dao.positionDao;
import entity.Administrator;
import entity.AdministratorPower;
import entity.Position;
import entity.Power;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import pojo.StateBean;
import pojo.tree;
import sun.reflect.generics.tree.Tree;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

@Controller
@RequestMapping("/role")
public class role {
    @Autowired
    private AdministratorDao administratorDao;
    @Autowired
    private positionDao positionDao;
    @Autowired
    public AdministratorPowerDao administratorPowerDao;
    @Autowired
    public PowerDao powerDao;

    @RequestMapping("/showRole")
    @ResponseBody
    public Map<String, Object> showRole(String roleName, String positionId, int offset, int limit) {//展示所有的用户可按条件查询
        try {
            if (roleName != null) {
                roleName = new String(roleName.getBytes("ISO-8859-1"), "utf-8");
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (positionId == null) {
            positionId = "0";
        }
        Map<String, Object> map = new HashMap<>();
        map.put("rows", administratorDao.showRole(roleName, Integer.parseInt(positionId), offset, limit));
        map.put("total", administratorDao.total(roleName, Integer.parseInt(positionId)));
        return map;
    }

    @RequestMapping("/showPosition")//查看所有的职位
    @ResponseBody
    public List<Position> showPosition() {//展示所有的职位
        return positionDao.showPosition();
    }

    // uploadFile
    @RequestMapping("/uploadFile")//头像上传
    @ResponseBody
    public Map<String, Object> uploadFile(MultipartFile myfile, HttpServletRequest request)
            throws IllegalStateException, IOException {
        // 原始名称
        String oldFileName = myfile.getOriginalFilename(); // 获取上传文件的原名
        /*System.out.println(oldFileName);*/
        // 存储图片的虚拟本地路径（这里需要配置tomcat的web模块路径，双击猫进行配置）
        String saveFilePath = "D:\\Y2\\SYiphone\\src\\main\\webapp\\image";
        // 上传图片
        if (myfile != null && oldFileName != null && oldFileName.length() > 0) {
            // 新的图片名称
            String newFileName = UUID.randomUUID() + oldFileName.substring(oldFileName.lastIndexOf("."));
            // 新图片
            File newFile = new File(saveFilePath + "\\" + newFileName);
            // 将内存中的数据写入磁盘
            myfile.transferTo(newFile);
            // 将新图片名称返回到前端
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("success", "成功啦");
            map.put("url", newFileName);
            return map;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("error", "图片不合法");
            return map;
        }
    }

    @RequestMapping("/adduser")//添加用户
    @ResponseBody
    public Map<String, Object> addAdministrator(Administrator admin) {
        administratorDao.adduser(admin);
        return showRole(null, "0", 0, 7);
    }

    @RequestMapping("/deluser")//批量删除
    @ResponseBody
    public Map<String, Object> deluser(String id) {
        id = id.substring(0, id.length() - 1);//去掉最后一个字符
        String[] ids = id.split(",");//根据,拆分成数组
        for (int i = 0; i < ids.length; i++) {
            administratorDao.deluser(Integer.parseInt(ids[i]));
        }
        return showRole(null, "0", 0, 7);
    }

    @RequestMapping("/upuser")//修改用户
    @ResponseBody
    public Map<String, Object> upAdministrator(Administrator admin) {//修改管理员
        administratorDao.upuser(admin);
        return showRole(null, "0", 0, 7);
    }

    @RequestMapping("/treeBean")//查看权限
    @ResponseBody
    public List<tree> trees(String aid) {
        //得到当前用户所有的权限
        List<tree> treeList = administratorPowerDao.showQuery(Integer.parseInt(aid));
        List<tree> listA = powerDao.showmenu();//得到所有的父级
       /* List<tree> lists = new ArrayList<>();*/
        tree trees;
        for (tree ta : listA) {
            StateBean stateBean = new StateBean();
            for (tree treelist : treeList) {//判断用户是否有这个权限 //回显当前角色拥有的所有权限
                if (ta.getId() == treelist.getId()) {
                    stateBean.setChecked(true);
                }
                ta.setState(stateBean);
            }
            List<tree> listB = powerDao.showpermission(ta.getId());//得到该父级下的子级

            for (tree btree : listB) {
                StateBean stateBean1 =new StateBean();
                for (tree treelist : treeList) {//判断用户是否有这个权限 //回显当前角色拥有的所有权限
                    if (btree.getId() == treelist.getId()) {
                        stateBean1.setChecked(true);
                    }
                    btree.setState(stateBean1);
                }
            }
             ta.setNodes(listB);
            }
            return listA;
        }
    @RequestMapping("/addtreeBean")//先删除权限在添加权限
    @ResponseBody
        public Map<String,Object> grantPermission(int aids,String roleId){
            Map<String,Object> map = new HashMap<>();
            try {
                String[] ss = roleId.split("-") ;
                int[] perids = new int[ss.length-1] ;
                for(int i=0;i<perids.length;i++){
                    perids[i] = Integer.parseInt(ss[i+1]) ;
                }
                //删除角色对应的权限
                administratorPowerDao.delpower(aids);
                //增加用户选 择的权限
                for(int i=0; i<perids.length;i++) {
                    administratorPowerDao.addpower(aids,perids[i]);
                }
                map.put("msg","1") ;
            } catch (NumberFormatException e) {
                map.put("msg","2") ;
                e.printStackTrace();
            }
            return map;
        }

}
